package com.sptus.mqtt;

import java.util.Map;

import javax.annotation.PostConstruct;

import com.sptus.common.utils.uuid.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import com.sptus.framework.mqtt.MyMqttClient;

@Configuration
//@Profile({"dev","local"})
public class MqttConfig {

    @Value("${spring.mqtt.enable}")
    private Boolean enableFlag;

    @Value("${spring.mqtt.url}")
    private String hostUrl;

    @Value("${spring.mqtt.username}")
    private String username;

    @Value("${spring.mqtt.password}")
    private String password;

    @Value("${spring.mqtt.clientId}")
    private String clientId;

    @Value("${spring.mqtt.trustStorePath}")
    private String trustStorePath;

    @Value("${spring.mqtt.trustStorePassword}")
    private String trustStorePassword;

    @Value("${spring.mqtt.keyStorePath}")
    private String keyStorePath;

    @Value("${spring.mqtt.keyStorePassword}")
    private String keyStorePassword;



    // 全局变量
    private static Map<String, String> globalData;

    private String generateUniqueClientId() {
        String baseClientId = this.clientId;
        String uniqueSuffix = UUID.randomUUID().toString().substring(0, 8) +
                "_" + System.currentTimeMillis();
        return baseClientId + "_" + uniqueSuffix;
    }

    @PostConstruct
    public void loadData() throws Exception {
//
//
//
////        String serviceUrl = "tcp://mqtt.sptcssc.com:1883";
////        String userName = "spt.mqtt";
////        String password = "spt.mqtt";
////        String clientId = "spt.mqtt";
        String serviceUrl = hostUrl;
        String userName = username;
//        String password = this.password;
//        String clientId = this.clientId;
////         创建对象

        String uniqueClientId = generateUniqueClientId();

        MyMqttClient mqttClient = new MyMqttClient(serviceUrl, userName, password, uniqueClientId,trustStorePath,trustStorePassword,keyStorePath,keyStorePassword,new MqttIotCallback());
        // mqttClient类初始化
        mqttClient.init();
        // 订阅主题
        mqttClient.subscribeTopic("/#", 0);
    }

    public static Map<String, String> getGlobalData() {
        return globalData;
    }
}
